﻿using System;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using Csla;
using Csla.Rules;
using Csla.Rules.CommonRules;
using Csla.Server;
using BizControl.DalLinq;
using Csla.Data;
using Csla.Reflection;
using System.Data.Linq;
using BizControl.Library.BusinessObjects.People;
using BizControl.Library.Security;
using BizControl.Resources;
using System.Security;

namespace BizControl.Library.BusinessObjects.Models
{
  [Serializable]
  public class ModelBO : BusinessBase<ModelBO>, ISupportEmptyValue
  {
    #region Business Methods

    private static readonly PropertyInfo<Guid> ModelIdProperty = RegisterProperty<Guid>(c => c.ModelId);
    [Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(ValidationErrors), ErrorMessageResourceName = @"ModelModelIdRequiredPropertyError")]
    public Guid ModelId
    {
      get { return GetProperty(ModelIdProperty); }
      private set { SetProperty(ModelIdProperty, value); }
    }

    private static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(c => c.Name);
    [Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(ValidationErrors), ErrorMessageResourceName = @"ModelNameRequiredPropertyError")]
    [StringLength(50, ErrorMessageResourceType = typeof(ValidationErrors), ErrorMessageResourceName = @"ModelNameLengthPropertyError")]
    [Display(ResourceType = typeof(PropertiesNames), Name = @"ModelNameProperty")]
    public string Name
    {
      get { return GetProperty(NameProperty); }
      set { SetProperty(NameProperty, value); }
    }

    #region Common properties

    private static readonly PropertyInfo<bool> IsDeletedFieldProperty = RegisterProperty<bool>(c => c.IsDeletedField, null, false);
    [Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(ValidationErrors), ErrorMessageResourceName = @"IsDeletedRequiredError")]
    [Display(ResourceType = typeof(PropertiesNames), Name = @"IsDeletedFieldProperty")]
    public bool IsDeletedField
    {
      get { return GetProperty(IsDeletedFieldProperty); }
      private set { SetProperty(IsDeletedFieldProperty, value); }
    }

    private static readonly PropertyInfo<PersonInfo> CreatedByProperty = RegisterProperty<PersonInfo>(c => c.CreatedBy);
    [Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(ValidationErrors), ErrorMessageResourceName = @"CreatedByRequiredPropertyError")]
    [Display(ResourceType = typeof(PropertiesNames), Name = @"CreatedByProperty")]
    public PersonInfo CreatedBy
    {
      get { return GetProperty(CreatedByProperty); }
      private set { SetProperty(CreatedByProperty, value); }
    }

    private static readonly PropertyInfo<DateTime> CreatedOnProperty = RegisterProperty<DateTime>(c => c.CreatedOn);
    [Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(ValidationErrors), ErrorMessageResourceName = @"CreatedOnRequiredPropertyError")]
    [Display(ResourceType = typeof(PropertiesNames), Name = @"CreatedOnProperty")]
    public DateTime CreatedOn
    {
      get { return GetProperty(CreatedOnProperty); }
      private set { SetProperty(CreatedOnProperty, value); }
    }

    private static readonly PropertyInfo<DateTime> LastChangedProperty = RegisterProperty<DateTime>(c => c.LastChanged);
    [Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(ValidationErrors), ErrorMessageResourceName = @"LastChangedRequiredPropertyError")]
    [Display(ResourceType = typeof(PropertiesNames), Name = @"LastChangedProperty")]
    public DateTime LastChanged
    {
      get { return GetProperty(LastChangedProperty); }
      private set { SetProperty(LastChangedProperty, value); }
    }

    private static readonly PropertyInfo<PersonInfo> LastChangedByProperty = RegisterProperty<PersonInfo>(c => c.LastChangedBy);
    [Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(ValidationErrors), ErrorMessageResourceName = @"LastChangedByRequiredPropertyError")]
    [Display(ResourceType = typeof(PropertiesNames), Name = @"LastChangedByProperty")]
    public PersonInfo LastChangedBy
    {
      get { return GetProperty(LastChangedByProperty); }
      private set { SetProperty(LastChangedByProperty, value); }
    }

    private static readonly PropertyInfo<byte[]> TimeStampProperty = RegisterProperty<byte[]>(c => c.TimeStamp);
    private byte[] TimeStamp
    {
      get { return GetProperty(TimeStampProperty); }
      set { SetProperty(TimeStampProperty, value); }
    }

    #endregion

    #region Children

    private static readonly PropertyInfo<ModelPeople> PeopleProperty = RegisterProperty<ModelPeople>(p => p.People, RelationshipTypes.Child | RelationshipTypes.LazyLoad);
    public ModelPeople People
    {
      get
      {
        if (!(FieldManager.FieldExists(PeopleProperty)))
          People = ModelPeople.NewModelPeople(this);
        return GetProperty(PeopleProperty);
      }
      set
      {
        LoadProperty(PeopleProperty, value);
        OnPropertyChanged(PeopleProperty);
      }
    }

    #endregion

    internal void LoadData(Model modelDB)
    {
      if (modelDB == null) return;
      ModelId = modelDB.ModelId;
      Name = modelDB.Name;
      // Common properties
      CreatedBy = new PersonInfo(modelDB.CreatedByRef);
      LastChangedBy = new PersonInfo(modelDB.LastChangedByRef);

      CreatedOn = modelDB.CreatedOn;
      LastChanged = modelDB.LastChanged;
      IsDeletedField = modelDB.IsDeleted;
      TimeStamp = modelDB.TimeStamp.ToArray();
    }

    public override string ToString()
    {
      return Name;
    }

    #endregion

    #region Business Rules

    protected override void AddBusinessRules()
    {
      base.AddBusinessRules();
    }

    #endregion

    #region Authorization rules

    private static void AddObjectAuthorizationRules()
    {
      //BusinessRules.AddRule(typeof(ModelBO), new IsInRole(AuthorizationActions.CreateObject, "ModelBO.Create()"));
      //BusinessRules.AddRule(typeof(ModelBO), new IsInRole(AuthorizationActions.GetObject, "ModelBO.Get()"));
      //BusinessRules.AddRule(typeof(ModelBO), new IsInRole(AuthorizationActions.EditObject, "ModelBO.Edit()"));
      //BusinessRules.AddRule(typeof(ModelBO), new IsInRole(AuthorizationActions.DeleteObject, "ModelBO.Delete()"));
    }

    #endregion

    #region Data Access

    //[RunLocal]
    protected override void DataPortal_Create()
    {
      var currentUser = SecurityChecks.GetCurrentUser();
      using (BypassPropertyChecks)
      {
        ModelId = Guid.NewGuid();
        CreatedBy = new PersonInfo(currentUser);
        LastChangedBy = new PersonInfo(currentUser);
        CreatedOn = DateTime.Now;
      }
      base.DataPortal_Create();
    }

    private void DataPortal_Fetch(SingleCriteria<ModelBO, Guid> id)
    {
      using (var ctx = ContextManager<BusinessControl2DataContext>.GetManager(Database.BizControlDB))
      {
        var data = (from m in ctx.DataContext.Models
                    where m.ModelId == id.Value && !m.IsDeleted
                    select m).SingleOrDefault();
        using (BypassPropertyChecks)
        {
          this.LoadData(data);
        }
        if (data != null)
        {
          People = ModelPeople.GetModelPeople(data.ModelPeople.ToArray(), this);
        }
      }
    }

    [Transactional(TransactionalTypes.TransactionScope)]
    protected override void DataPortal_Insert()
    {
      using (var ctx = ContextManager<BusinessControl2DataContext>.GetManager(Database.BizControlDB))
      {
        Binary lastTimeStamp = null;
        LastChanged = DateTime.Now;
        using (BypassPropertyChecks)
        {
          ctx.DataContext.AddModel(
            ModelId,
            Name,
            CreatedBy == null || CreatedBy.IsEmpty() ? (Guid?)null : CreatedBy.Id,
            IsDeletedField,
            CreatedOn,
            LastChanged,
            LastChangedBy == null || LastChangedBy.IsEmpty() ? (Guid?)null : LastChangedBy.Id,
            ref lastTimeStamp);
          TimeStamp = lastTimeStamp.ToArray();
        }
        // update child objects
        Csla.DataPortal.UpdateChild(People, this);
        //FieldManager.UpdateChildren(this);
      }
    }

    [Transactional(TransactionalTypes.TransactionScope)]
    protected override void DataPortal_Update()
    {
      using (var ctx = ContextManager<BusinessControl2DataContext>.GetManager(Database.BizControlDB))
      {
        if (IsSelfDirty)
        {
          Binary lastTimeStamp = null;
          LastChangedBy = new PersonInfo(SecurityChecks.GetCurrentUser());
          LastChanged = DateTime.Now;
          using (BypassPropertyChecks)
          {
            ctx.DataContext.UpdateModel(
              ModelId,
              Name,
              IsDeletedField,
              LastChanged,
              LastChangedBy == null || LastChangedBy.IsEmpty() ? (Guid?)null : LastChangedBy.Id,
              TimeStamp,
              ref lastTimeStamp);
            TimeStamp = lastTimeStamp.ToArray();
          }
        }
        // update child objects
        FieldManager.UpdateChildren(this);
      }
    }

    [Transactional(TransactionalTypes.TransactionScope)]
    protected override void DataPortal_DeleteSelf()
    {
      DataPortal_Delete(new SingleCriteria<ModelBO, Guid>(ModelId));
    }

    [Transactional(TransactionalTypes.TransactionScope)]
    private void DataPortal_Delete(SingleCriteria<ModelBO, Guid> criteria)
    {
      IsDeletedField = true;
      DataPortal_Update();
    }

    #endregion

    #region Factory Methods

    private ModelBO()
    { /* require use of factory methods */ }

    public static ModelBO NewModel()
    {
      return Csla.DataPortal.Create<ModelBO>();
    }

    public static ModelBO GetModel(Guid id)
    {
      return Csla.DataPortal.Fetch<ModelBO>(new SingleCriteria<ModelBO, Guid>(id));
    }

    #endregion


    #region ISupportEmtpyValue Members

    public bool IsEmpty()
    {
      return ModelId == Guid.Empty;
    }

    #endregion
  }
}
